package 数组;

/**
 * @author ssh
 * @date 2025/9/18
 * @description
 */
public class 移除元素 {
    public int removeElement(int[] nums, int val) {
        int left = 0; // 慢指针，指向下一个不等于 val 的位置
        for(int right=0;right<nums.length;right++){
            if (nums[right]!=nums[val]){
                nums[left]=nums[right];
                left++;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        移除元素 solution = new 移除元素();
        int[] nums = {3, 2, 2, 3};
        int val = 3;
        int newLength = solution.removeElement(nums, val);
        System.out.println("New length: " + newLength); // 输出: New length: 2
        System.out.print("Modified array: ");
        for (int i = 0; i < newLength; i++) {
            System.out.print(nums[i] + " "); // 输出: Modified array: 2 2
        }
    }
}
